---
title: "Jofré & Cabezas 2024"
subtitle: "DADOS Replication Material"
author: "José M. Cabezas - jcabezas@umd.edu"
date: "Agosto 16 2024"
output: html_document
---

```{r setup, include=F, message=F, results=F, error=F}
rm(list=ls())
knitr::opts_chunk$set(echo=T, message=F, results=F, error=F)
```

```{r preamble}
# Required packages
if(!require(readxl)){install.packages("readxl")}
if(!require(readr)){install.packages("readr")}
if(!require(stargazer)){install.packages("stargazer")}
if(!require(ggplot2)){install.packages("ggplot2")}
if(!require(janitor)){install.packages("janitor")}
if(!require(knitr)){install.packages("knitr")}
if(!require(purrr)){install.packages("purrr")}
if(!require(dplyr)){install.packages("dplyr")}
```


## Dataset

```{r legislators}
#legislators <- readr::read_delim('JofreCabezasDADOS2024.csv', delim=";") %>% arrange(year, distrito)
legislators <- readxl::read_excel('240820_JofreCabezasDADOS2024.xlsx') %>%
  janitor::clean_names() %>%
  arrange(year, distrito)
dplyr::glimpse(legislators)
```





### Malapportionment
#### Lists
```{r}
mal_l <- 
legislators %>% 
  select(year, distrito, dm, lista, voteslista, pvoteslista, elected_list) %>% 
  group_by(year, distrito, dm, lista) %>% 
  summarise_all(min) %>% 
  mutate(si=elected_list/dm,
         ratio=abs(si-pvoteslista),
         check=sum(pvoteslista)) %>% 
  group_by(year, distrito) %>% 
  mutate(mal=(sum(ratio))*.5,
         type='Listas')

dplyr::glimpse(mal_l)
```

#### Parties
```{r}
mal_p <- 
  legislators %>% 
  select(year, distrito, dm, party, votespartido, pvotespartido, elected_party) %>% 
  group_by(year, distrito, dm, party) %>% 
  summarise_all(min) %>% 
  mutate(si=elected_party/dm,
         ratio=abs(si-pvotespartido),
         check=sum(pvotespartido)) %>% 
  group_by(year, distrito) %>% 
  mutate(mal=(sum(ratio))*.5,
         type='Partidos')

dplyr::glimpse(mal_p)
```



### Effective Number
#### Lists
```{r}
nep_l <- 
  legislators %>% 
  select(year, distrito, lista, pvoteslista) %>% 
  group_by(year, distrito, lista) %>% 
  summarise_all(min) %>% 
  mutate(nep=1/sum(pvoteslista^2),
         type="Listas")

dplyr::glimpse(nep_l)
```

#### Parties
```{r}
nep_p <- 
  legislators %>% 
  select(year, distrito, party, pvotespartido) %>% 
  group_by(year, distrito, party) %>% 
  summarise_all(min) %>% 
  mutate(nep=1/sum(pvotespartido^2), 
         type="Partidos")

dplyr::glimpse(nep_p)
```

## OLS
### Malapportionment
#### Lists
```{r}
ols_mal_l <- lm(mal ~ reforma + as.factor(-year), data=mal_l %>%
                  mutate(reforma=if_else(year<=2013,0,1)))
```

#### Parties
```{r}
ols_mal_p <- lm(mal ~ reforma + as.factor(-year), data=mal_p %>%
                      mutate(reforma=if_else(year<=2013,0,1)))
```


### ENP
#### Lists
```{r}
ols_nep_l <- lm(nep ~ reforma +  as.factor(year), data=legislators %>% 
                              select(year, distrito, lista, pvoteslista) %>% 
                              group_by(year, distrito, lista) %>% 
                              summarise_all(min) %>% 
                              mutate(nep=1/sum(pvoteslista^2),
                                     reforma=if_else(year<=2013,0,1)) )
```

#### Parties
```{r}
ols_nep_p <- lm(nep ~ reforma +  as.factor(year), data=legislators %>% 
                              select(year, distrito, party, pvotespartido) %>% 
                              group_by(year, distrito, party) %>% 
                              summarise_all(min) %>% 
                              mutate(nep=1/sum(pvotespartido^2),
                                     reforma=if_else(year<=2013,0,1)) )
```



## OLS Table
```{r, results='asis'}
stargazer::stargazer(ols_nep_p, ols_nep_l, ols_mal_p, ols_mal_l,
                     column.labels=c("Partidos", "Listas", "Partidos", "Listas"),
                     covariate.labels="Reforma",
                     omit=c(3,4),
                     omit.stat=c("F", "ser"),
                     notes="Notas: Efectos fijos por años",
                     notes.align="c",
                     no.space=T, 
                     type="html",
                     out="ols.html")
```

```{r}
stargazer::stargazer(ols_nep_p, ols_nep_l, ols_mal_p, ols_mal_l, no.space=T, type="text")
```

## Figures
### Fig 1
```{r}
bind_rows(nep_p, nep_l)  %>%
  group_by(year, type) %>% 
  ggplot(aes(as.factor(year), nep)) +
  geom_boxplot() +
  ylim(1,14) +
  labs(#title="Número Efectivo",
    y="Número Efectivo",
    x="Elección de Diputadas y Diputados",
    caption="Elaboración y cálculos propios con datos SERVEL") +
  facet_wrap(~type)+
  theme_classic() +
  theme(plot.caption = element_text(hjust=0))
ggsave('nep.png', height=600, width=800, units="px", dpi=108)
```




### Fig 2
```{r}
bind_rows(mal_l, mal_p) %>%
  group_by(year, type) %>% 
  ggplot(aes(as.factor(year), mal)) +
  geom_boxplot() +
  labs(#title="Malapportionment",
       y="Malapportionment",
       x="Elección de Diputadas y Diputados",
       caption="Elaboración y cálculos propios con datos SERVEL") +
  facet_wrap(~type)+
  theme_classic() +
  theme(plot.caption = element_text(hjust=0))
ggsave('mal.png', height=600, width=800, units="px", dpi=108)
```



## Descriptive tables 4-9
### Table 4
```{r, echo=F}
legislators %>%
  filter(year==2009 & elected==1) %>% 
  count(lista)

legislators$coalitions <- NA


legislators$coalitions[legislators$lista=="A" & legislators$year==2009] <- "Concertación (PDC-PC-PS-PPD-PR)" 
legislators$coalitions[legislators$lista=="B" & legislators$year==2009] <- "Coalición por el Cambio (RN+UDI)" 
legislators$coalitions[legislators$lista=="D" & legislators$year==2009] <- "Vota Limpio, vote feliz (PRI)" 
legislators$coalitions[legislators$lista=="G" & legislators$year==2009] <- "Independiente fuera de pacto" 

legislators %>%
  filter(year==2009 & elected==1) %>% 
  count(coalitions)
  
```



```{r Table 4, echo=T, results='asis'}
legislators %>%
  filter(year==2009 & elected==1) %>% 
  tabyl(coalitions) %>% 
  adorn_pct_formatting(digits=1) %>%
  adorn_totals("row") %>% 
  knitr::kable(caption="Cuadro 4. Integrantes de la Cámara de Diputados 2009 por listas electorales",
               col.names=c("", "n", "porcentaje"),
               format="html")
```


### Table 5
```{r, echo=F}
legislators %>%
  filter(year==2013 & elected==1) %>% 
  count(lista)

legislators$coalitions[legislators$lista=="C" & legislators$year==2013] <- "Nueva Mayoría (PDC-PC-PS-PPD-PR)"
legislators$coalitions[legislators$lista=="I" & legislators$year==2013] <- "Si tú quieres, Chile cambia (PRO+Liberal)"
legislators$coalitions[legislators$lista=="J" & legislators$year==2013] <- "Alianza (RN+UDI)"
legislators$coalitions[legislators$lista=="L" & legislators$year==2013] <- "Independiente fuera de pacto" 

legislators %>%
  filter(year==2013 & elected==1) %>% 
  count(coalitions)
  
```

```{r Table 5, echo=T, results='asis'}
legislators %>%
  filter(year==2013 & elected==1) %>% 
  tabyl(coalitions) %>% 
  adorn_pct_formatting(digits=1) %>%
  adorn_totals("row") %>% 
  knitr::kable(caption="Cuadro 5. Integrantes de la Cámara de Diputados de 2013 por listas electorales",
               col.names=c("", "n", "porcentaje"),
               format="html")
```


### Table 6
```{r, echo=F}
legislators %>%
  filter(year==2017 & elected==1) %>% 
  count(lista)

legislators$coalitions[legislators$lista=="B" & legislators$year==2017] <- "Por todo Chile (PRO)"
legislators$coalitions[legislators$lista=="G" & legislators$year==2017] <- "Frente Amplio"
legislators$coalitions[legislators$lista=="K" & legislators$year==2017] <- "Regionalista Verde Social (FREVS)"
legislators$coalitions[legislators$lista=="N" & legislators$year==2017] <- "La Fuerza de la Mayoría (PC-PS-PPD-PR)"
legislators$coalitions[legislators$lista=="O" & legislators$year==2017] <- "Convergencia Democrática (PDC)"
legislators$coalitions[legislators$lista=="P" & legislators$year==2017] <- "Chile Vamos (RN+UDI+EVO+PRI)"
legislators$coalitions[legislators$lista=="R" & legislators$year==2017] <- "Independiente fuera de pacto"


legislators %>%
  filter(year==2017 & elected==1) %>% 
  count(coalitions)
  
```

```{r Table 6, echo=T, results='asis'}
legislators %>%
  filter(year==2017 & elected==1) %>% 
  tabyl(coalitions) %>% 
  adorn_pct_formatting(digits=1) %>%
  adorn_totals("row") %>% 
  knitr::kable(caption="Cuadro 6. Integrantes de la Cámara de Diputados en el 2017 por listas electorales",
               col.names=c("", "n", "porcentaje"),
               format="html")
```



### Table 7
```{r, echo=F}
legislators %>%
  filter(year==2021 & elected==1) %>% 
  count(lista)

legislators %>%
  filter(year==2021 & elected==1) %>% 
  count(lista, party) %>% print(n=100)

legislators$coalitions[legislators$lista=="AA CP+" & legislators$year==2021] <- "Chile Podemos + (RN+UDI+EVO+PRI)"
legislators$coalitions[legislators$lista=="AB. PDG" & legislators$year==2021] <- "Partido de la Gente"
legislators$coalitions[legislators$lista=="AH NPS" & legislators$year==2021] <- "Nuevo Pacto Social (PDC-PS-PPD-PR-LIB-CIU)"
legislators$coalitions[legislators$lista=="AL PEV" & legislators$year==2021] <- "Partido Ecologista Verde"
legislators$coalitions[legislators$lista=="AN DH" & legislators$year==2021] <- "Dignidad Ahora (Humanistas)"
legislators$coalitions[legislators$lista=="AP FSC" & legislators$year==2021] <- "Frente Social Cristiano"
legislators$coalitions[legislators$lista=="AR AD" & legislators$year==2021] <- "Apruebo Dignidad (PC-Frente Amplio)"
legislators$coalitions[legislators$lista=="AW IU" & legislators$year==2021] <- "Independientes Unidos (Centro Unido)"
legislators$coalitions[legislators$lista=="AZ IND" & legislators$year==2021] <- "Independiente fuera de pacto"
legislators$coalitions[legislators$lista=="xxx" & legislators$year==2021] <- "xxx"



legislators %>%
  filter(year==2021 & elected==1) %>% 
  count(coalitions)
  
```



```{r Table 7, echo=T, results='asis'}
legislators %>%
  filter(year==2021 & elected==1) %>% 
  tabyl(coalitions) %>% 
  adorn_pct_formatting(digits=1) %>%
  adorn_totals("row") %>% 
  knitr::kable(caption="Cuadro 7. Integrantes de la Cámara de Diputados en el 2021 por listas electorales",
               col.names=c("", "n", "porcentaje"),
               format="html")
```


### Table 9
```{r, echo=F}
# 2009
legislators$party[legislators$candidato_a=="ISASI BARBIERI MARTA ELIANA" & legislators$year==2009] <- "UDI"
legislators$party[legislators$candidato_a=="MOLINA OLIVA ANDREA" & legislators$year==2009] <- "UDI"
legislators$party[legislators$candidato_a=="ALVAREZ-SALAMANCA RAMIREZ PEDRO PABLO" & legislators$year==2009] <- "UDI"

legislators$party[legislators$candidato_a=="VARGAS PIZARRO ORLANDO" & legislators$year==2009] <- "PPD"

# 2013
legislators$party[legislators$candidato_a=="CICARDINI MILLA DANIELLA" & legislators$year==2013] <- "PS"
legislators$party[legislators$candidato_a=="AGUILO MELO SERGIO" & legislators$year==2013] <- "PS"
legislators$party[legislators$candidato_a=="POBLETE ZAPATA ROBERTO" & legislators$year==2013] <- "PS"
legislators$party[legislators$candidato_a=="FUENTES CASTILLO IVAN" & legislators$year==2013] <- "DC"


# 2017
legislators$party[legislators$candidato_a=="INDEPENDIENTE FEDERACION REGIONALISTA VERDE SOCIAL" & legislators$year==2017] <- "FEDERACION REGIONALISTA VERDE SOCIAL"
legislators$party[legislators$candidato_a=="INDEPENDIENTE EVOLUCION POLITICA" & legislators$year==2017] <- "EVOLUCION POLITICA"
legislators$party[legislators$candidato_a=="INDEPENDIENTE IGUALDAD" & legislators$year==2017] <- "IGUALDAD"
legislators$party[legislators$candidato_a=="INDEPENDIENTE RADICAL SOCIALDEMOCRATA" & legislators$year==2017] <- "RADICAL SOCIALDEMOCRATA"
legislators$party[legislators$candidato_a=="INDEPENDIENTE EVOLUCION POLITICA" & legislators$year==2017] <- "EVOLUCION POLITICA"
legislators$party[legislators$candidato_a=="INDEPENDIENTE RENOVACION NACIONAL" & legislators$year==2017] <- "RENOVACION NACIONAL"
legislators$party[legislators$candidato_a=="INDEPENDIENTE UNION DEMOCRATA INDEPENDIENTE" & legislators$year==2017] <- "UNION DEMOCRATA INDEPENDIENTE"
legislators$party[legislators$candidato_a=="INDEPENDIENTE RENOVACION NACIONAL" & legislators$year==2017] <- "RENOVACION NACIONAL"
legislators$party[legislators$candidato_a=="INDEPENDIENTE POR LA DEMOCRACIA" & legislators$year==2017] <- "POR LA DEMOCRACIA"
legislators$party[legislators$candidato_a=="INDEPENDIENTE HUMANISTA" & legislators$year==2017] <- "HUMANISTA"
legislators$party[legislators$candidato_a=="INDEPENDIENTE RADICAL SOCIALDEMOCRATA" & legislators$year==2017] <- "RADICAL SOCIALDEMOCRATA"


legislators$party[legislators$party=="INDEP" & legislators$year==2009] <- "IND"
legislators$party[legislators$party=="INDEP" & legislators$year==2013] <- "IND"

legislators %>%
  filter(elected==1) %>% 
  tabyl(party, year) %>% 
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns %>%
  adorn_title

legislators %>%
  filter(elected==1) %>% 
  tabyl(party, year)  %>% 
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits=1)


```


```{r Table 9, echo=T, results='asis'}
legislators %>%
  filter(elected==1) %>% 
  tabyl(party, year) %>% 
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns %>%
  knitr::kable(caption="Cuadro 9. Representación partidaria de la Cámara de Diputados (2009-2021)",
               format="html")
```


### Table(s) 8
```{r, echo=T, results='asis'}
legislators %>%
  mutate(sex=if_else(sex==0, "Hombre", "Mujer")) %>% 
  tabyl(sex, year) %>% 
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns %>%
  knitr::kable(caption="Cuadro 8. Estadísticos descriptivos de la Cámara de Diputados (2009-2021) CANDIDATOS",
               col.names=c("", "2009", "2013", "2017", "2021"),
               format="html")
```



```{r, echo=T, results='asis'}
legislators %>%
  filter(elected==1) %>% 
  mutate(sex=if_else(sex==0, "Hombre", "Mujer")) %>%
  tabyl(sex, year) %>% 
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns %>%
  knitr::kable(caption="Cuadro 8. Estadísticos descriptivos de la Cámara de Diputados (2009-2021) DIPUTADOS/AS",
               col.names=c("", "2009", "2013", "2017", "2021"),
               format="html")
```


```{r, echo=T, results='asis'}
legislators %>%
  filter(elected==1) %>% 
  mutate(sex=if_else(incumbent==1, "Incumbente", "Desafiante", NA)) %>%
  tabyl(sex, year) %>% 
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns %>%
  knitr::kable(caption="Cuadro 8. Estadísticos descriptivos de la Cámara de Diputados (2009-2021) DIPUTADOS/AS",
               col.names=c("", "2009", "2013", "2017", "2021"),
               format="html")
```




```{r}

```

